package com.carlinfo.stu_ques.users.dao.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import com.carlinfo.stu_ques.common.dao.impl.BaseDaoImpl;
import com.carlinfo.stu_ques.common.util.FileUtil;
import com.carlinfo.stu_ques.demo.pojo.King;
import com.carlinfo.stu_ques.users.dao.IStudentDao;
import com.carlinfo.stu_ques.users.pojo.Students;

public class StudentDaoImpl extends BaseDaoImpl<Students> implements IStudentDao {
	
	private File resultfile = new File(this.parentFile,"studentsSource.dat");
	
	/**
	 * 无参的构造函数，被实例化时先运行，将其中的值取出来
	 */
	public StudentDaoImpl() {
		this.readFile(resultfile);
	}

	/**
	 * 存储一条学生
	 */
	@Override
	public int saveOneDao(Students stu) {
		stu.setId(this.id);
		temId = stu.getId();
		super.saveOneDao(stu);
		this.writeFile(resultfile);
		return this.temId;
	}

	/**
	 * 更新一条记录
	 */
	@Override
	public void updateOneDao(Students stu) {
		
		this.temId = stu.getId();
		super.updateOneDao(stu);
		this.writeFile(resultfile);
	}

	/**
	 * 删除一条记录
	 */
	@Override
	public void deleteOneDao(Students stu) {
		this.temId = stu.getId();
		super.deleteOneDao(stu);
		this.writeFile(resultfile);	
	}

	@Override
	public boolean dbToFile(String path)
	{	
		Connection conn = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		try
		{
			Map<Integer, Object> map = new TreeMap<Integer, Object>();
			List<Object> list = new ArrayList<Object>();
			File file = new File(path);
			FileOutputStream fos = new FileOutputStream(file+"\\studentsSource.dat");
			FileUtil fileUtil = new FileUtil();
			/* 准备一条sql语句查询所有朝代 */
			String sql = "select * from students;";
			conn = dbUtil.getConnection();
			pst = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
			rs = pst.executeQuery();
			int id = 0;
			/* 将数据库中的数据取出来 */
			while(rs.next())
			{
				Students student = new Students();	
				id = rs.getInt("id");
				student.setName(rs.getString("name"));
				student.setId(id);
				student.setSex(rs.getString("sex"));
				student.setBirth(rs.getTimestamp("birth"));
				student.setScore(rs.getDouble("score"));
				student.setTotalCount(rs.getInt("totalConut"));
				student.setCountTrue(rs.getInt("countTrue"));
				student.setCountFalse(rs.getInt("countFalse"));
				student.setAccuracy(rs.getDouble("accuracy"));
				student.setTodayCount(rs.getInt("todayCount"));
				student.setTodayTrueCount(rs.getInt("todayTrueCount"));
				student.setTodayFalseCount(rs.getInt("todayFalseCount"));
				student.setTodayAccuracy(rs.getDouble("todayAccuracy"));
				student.setLevelId(rs.getInt("levelId"));
				student.setGraduateSchool(rs.getString("graduateSchool"));
				student.setCreateTime(rs.getTimestamp("createTime"));
				student.setUpdateTime(rs.getTimestamp("updateTime"));
				/* 将数据按照id放入map中 */
				map.put(id, student);
			}
			/* 将sql语句关闭 */
			pst.close();
			rs.close();
			/* 查询id最大值 */
			sql = "select max(id) from students;";
			pst = conn.prepareStatement(sql);
			rs = pst.executeQuery();
			if(rs.next())
			{
				/* 将map和id最大值放入文件 */
				list.add(map);
				list.add(rs.getInt(1)+1);
				System.out.println("最大id："+rs.getInt(1));
			}
			/* 将数据写到文件中去 */
			fileUtil.writeObject(fos, list);
			return true;
		} catch (IOException e)
		{
			e.printStackTrace();
		} catch (SQLException e)
		{
			e.printStackTrace();
		} finally
		{
			/* 关闭链接 */
			dbUtil.closeAll(pst, conn, rs);
		}
		return false;
	}

	@Override
	public boolean fileToDb()
	{	
		
		List<Students> list = this.selectListDao();
		if(list.size()!=0) {
			Connection conn = null;
			PreparedStatement pst = null;
			/* 每一次存之前,先将表清空 */
			String sql = "truncate table students;";
			/* 获取连接 */
			conn = dbUtil.getConnection();
			try
			{
				pst = conn.prepareStatement(sql);
				pst.executeUpdate();
				pst.close();
				sql = "INSERT INTO `students`(`name`, `sex`, `birth`, `graduateSchool`, `score`, `totalConut`, `countTrue`, `countFalse`, `accuracy`, `todayCount`, `todayTrueCount`, `todayFalseCount`, `todayAccuracy`, `levelId`, `createTime`, `updateTime`) "
						+ "VALUES (?,?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
				pst = conn.prepareStatement(sql);
				for (Students student : list)
				{
					pst.setObject(1,student.getName());
					pst.setObject(2,student.getSex());
					pst.setObject(3, student.getBirth());
					pst.setObject(4,student.getGraduateSchool());
					pst.setObject(5, student.getScore());
					pst.setObject(6, student.getTotalCount());
					pst.setObject(7, student.getCountTrue());
					pst.setObject(8, student.getCountFalse());
					pst.setObject(9, student.getAccuracy());
					pst.setObject(10, student.getTodayCount());
					pst.setObject(11, student.getTodayTrueCount());
					pst.setObject(12, student.getTodayFalseCount());
					pst.setObject(13, student.getTodayAccuracy());
					pst.setObject(14, student.getLevelId());
					pst.setObject(15, student.getCreateTime());
					pst.setObject(16, student.getUpdateTime());
					pst.addBatch();				
				}
				pst.executeBatch();
				pst.clearBatch();
				return true;
			} catch (SQLException e)
			{
				e.printStackTrace();
			} finally
			{
				/* 关闭链接 */
				dbUtil.closeAll(pst, conn, null);
			}
		} else
		{
			System.out.println("该文件是空的，没有数据可以插入");
		}
		return false;
	
	}


}
